/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package DAO;

import Entidad.Persona;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;

/**
 *
 * @author Jhon
 */
public class PersonaDAO {
 private static PersonaDAO INSTANCE = null;
     private synchronized static void createInstance() {
        if (INSTANCE == null) {
            INSTANCE = new PersonaDAO();
        }
    }
    public static PersonaDAO getInstance() {
        if (INSTANCE == null) createInstance();
        return INSTANCE;
    }
    EntityManagerFactory emf = Persistence.createEntityManagerFactory("AUM_S&SPU");

    public void Create(Object object) {
        EntityManager em = emf.createEntityManager();
        try {
            em.getTransaction().begin();
            em.persist(object);
            em.getTransaction().commit();
        } catch (Exception e) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", e);
            em.getTransaction().rollback();
        } finally {
            em.close();
        }
    }

    public void Update(Object object) {
        EntityManager em = emf.createEntityManager();
        try {
            em.getTransaction().begin();
            em.merge(object);
            em.getTransaction().commit();
        } catch (Exception e) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", e);
            em.getTransaction().rollback();
        } finally {
            em.close();
        }
    }

    public void Delete(Object object) {
        EntityManager em = emf.createEntityManager();
        try {
            em.getTransaction().begin();
            em.remove(object);
            em.getTransaction().commit();
        } catch (Exception e) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", e);
            em.getTransaction().rollback();
        } finally {
            em.close();
        }
    }

    public Persona getByID(String doc){
        EntityManager em = emf.createEntityManager();
        try {
        Query q = em.createQuery("SELECT a.* FROM persona a WHERE a.idPersona =  :doc");
        q.setParameter("doc", doc);
        return (Persona) q.getSingleResult();
        } catch (Exception e) {
            return null;
        }
    }

}
